<template>
  <div class="wrapper">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="帖子标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="帖子简介" prop="description">
        <v-md-editor v-model="ruleForm.description" height="300px"></v-md-editor>
      </el-form-item>
      <el-form-item label="帖子正文" prop="content">
        <v-md-editor v-model="ruleForm.content" height="300px"></v-md-editor>
      </el-form-item>
      <el-form-item label="帖子分类" prop="type">
        <el-checkbox-group v-model="ruleForm.type">
          <el-checkbox name="type" v-for="(item,index) in arr" :key="index" :label="item.label">{{item.res}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">发帖！！！！</el-button>
        <el-button @click="resetForm(ruleFormRef)">算了重写...</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElForm, ElMessage, ElNotification } from 'element-plus'
import getTime from '../utils/time'
import { write, getArticleInfo, Rewrite } from '../api/index'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

type FormInstance = InstanceType<typeof ElForm>

// 表单的接口
interface interfaceRuleForm {
  title: string
  description: string
  content: string
  type: (string | number)[]
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<interfaceRuleForm>({
  title: '',
  description: '',
  content: '',
  type: [],
})

// 分类接口
interface Item {
  label: number
  res: string
}
interface List {
  // key值是string类型的数组就是对象字面量
  [index: number]: Item
}

onMounted(() => {
  if (route.query.id) {
    getArticleInfo(route.query.id as string).then((res) => {
      const data = res.data.data[0]
      for (let key in data) {
        if (key == 'type') {
          data[key] = data[key].split(',')
          for (let i = 0; i < data[key].length; i++) {
            ruleForm.type.push(parseInt(data[key][i]))
          }
        } else {
          ruleForm[key] = data[key]
        }
      }
    })
  }
})
// 分类，死数据
const arr = reactive<List>([
  { label: 1, res: '前端' },
  { label: 2, res: '后端' },
  { label: 3, res: 'Android' },
  { label: 4, res: 'IOS' },
  { label: 5, res: '算法' },
  { label: 6, res: '开发工具' },
])

const rules = reactive({
  title: [
    {
      required: true,
      message: '请输入帖子标题',
      trigger: 'change',
    },
  ],
  description: [
    {
      required: true,
      message: '请输入一些内容来描述你的帖子',
      trigger: 'change',
    },
  ],
  content: [
    {
      required: true,
      message: '请输入帖子正文',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '至少选择一个分类',
      trigger: 'change',
    },
  ],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const time = getTime()
  formEl.validate((valid) => {
    if (valid) {
      let createdBy = parseInt(localStorage.getItem('userId'))
      if (route.query.id) {
        Rewrite(
          ruleForm.title,
          ruleForm.description,
          ruleForm.content,
          ruleForm.type,
          time,
          parseInt(route.query.id as string)
        ).then((res) => {
          setTimeout(() => {
            router.push('/')
          }, 1000)
          ElMessage({
            message: res.data.msg,
            type: 'success',
            duration: 1000,
            showClose: true,
          })
        })
      } else {
        write(
          ruleForm.title,
          ruleForm.description,
          ruleForm.content,
          ruleForm.type,
          time,
          createdBy
        ).then((res) => {
          if (res.data.code == 200) {
            ElNotification({
              title: '2s后跳转首页',
              message: res.data.msg,
              position: 'bottom-right',
              type: 'success',
              duration: 2000,
            })
            setTimeout(() => {
              router.push('/')
            }, 2000)
          } else {
            ElNotification({
              title: '失败了~',
              message: res.data.msg,
              position: 'bottom-right',
              type: 'warning',
              duration: 2000,
            })
          }
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>


<style lang="scss" scoped>
.wrapper {
  width: 100%;
  height: 60rem;
  .el-form {
    margin: 1rem 0;
    .el-input {
      width: 15rem;
    }
    .v-md-editor {
      width: 80%;
    }
  }
}
</style>